package com.syp.lease.web.app.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syp.lease.model.entity.BrowsingHistory;
import com.syp.lease.web.app.mapper.BrowsingHistoryMapper;
import com.syp.lease.web.app.service.BrowsingHistoryService;
import com.syp.lease.web.app.vo.history.HistoryItemVo;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 针对表【browsing_history(浏览历史)】的数据库操作Service实现
 */
@Service
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {
    @Override
    public Page<HistoryItemVo> pageHistoryItemByUserId(Page<HistoryItemVo> page, Long userId) {
        return baseMapper.pageHistoryItemByUserId(page, userId);
    }

    @Override
    @Async
    public void saveHistory(Long userId, Long id) {
        // 判断是否已经保存过
        BrowsingHistory browsingHistory = lambdaQuery()
                .eq(BrowsingHistory::getUserId, userId)
                .eq(BrowsingHistory::getRoomId, id)
                .one();
        // 如果已经保存过，则更新时间
        if (browsingHistory != null) {
            browsingHistory.setBrowseTime(new Date());
            baseMapper.updateById(browsingHistory);
            return;
        }
        // 保存浏览记录
        baseMapper.insert(new BrowsingHistory(userId, id, new Date()));
    }
}